package com.xx.dao;

import com.xx.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AccountDaoImpl implements AccountDao {
    JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int addAccount(Account account) {
        String sql = "insert into account(username, balance) values(?,?)";
        Object[] obj = new Object[]{account.getUsername(), account.getBalance()};
        return this.jdbcTemplate.update(sql, obj);
    }

    @Override
    public int updateAccount(Account account) {
        String sql = "update account set username=?,balance=? where id = ?";
        Object[] params = new Object[]{account.getUsername(), account.getBalance(), account.getId()};
        return this.jdbcTemplate.update(sql, params);
    }

    @Override
    public int deleteAccount(int id) {
        String sql = "delete from account where id = ?";
        return this.jdbcTemplate.update(sql, id);
    }

    @Override
    public Account findAccountById(int id) {
        String sql = "select * from account where id = ?";
        BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);

        return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
    }

    @Override
    public List<Account> findAllAccount() {
        String sql = "select * from account";
        BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<Account>(Account.class);

        return this.jdbcTemplate.query(sql, rowMapper);
    }

    @Override
    public void transfer(int outId, int inId, Double money) {
        this.jdbcTemplate.update("update account set balance = balance + ? where id = ?", money, inId);
        // 模拟系统运行时的突发性问题
        int i = 1 / 0;
        // 汇款时，汇款用户的余额=现有余额-所汇金额
        this.jdbcTemplate.update("update account set balance = balance - ? where id = ?", money, outId);
    }
}
